//
// BackendManager.cs
//
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.Collections.Generic;

using Dashboard;

namespace Dashboard.Engine {

	public class BackendManager : IService {

		private List<Backend> backends = new List<Backend> ();

		public void Initialize ()
		{
			Engine.Log.Debug ("Starting backend manager");
			Engine.MessageBroker.Subscribe ("/event/*", typeof (ClueMessage), OnClueMessage);
		}

		public void Dispose ()
		{
			Engine.Log.Debug ("Stopping backend manager");
		}

		public void Register (Backend backend)
		{
			Engine.Log.Debug ("Registered {0}", backend.GetType ());
			backends.Add (backend);
		}

		private void OnClueMessage (Message message)
		{
			ClueMessage clue_message = message as ClueMessage;

			foreach (Backend backend in backends) {
				foreach (Rule rule in backend.Rules) {
					Engine.Log.Debug ("{0} has rule {1}", backend.GetType (), rule.Relationship);
					IEnumerable<Match> matches = rule.Query (clue_message);
					MatchMessage match_message = new MatchMessage ();

					foreach (Match match in matches)
						match_message.Matches.Add (match);

					if (match_message.Matches.Count > 0)
						Engine.MessageBroker.Send (match_message);
				}
			}
		}
	}
}
